package com.yimaxiaoerlang.module_signalling.core;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class YMRtmWebSocketClient extends WebSocketClient {
    private final String TAG = "YMRtmWebSocketClient";
    private URI serverUri;
    private YMIEvent iEvent;

    private boolean connectFlag = false;
    private final int HEARTBEAT_MESSAGE_TAG = 1;
    private final int RESTART_CONNECT_TAG = 2;
    private final String HEARTBEAT_MESSAGE = "2";
    private int reconnectionNum = 0;

    public YMRtmWebSocketClient(URI serverUri, YMIEvent iEvent) {
        super(serverUri);
        this.serverUri = serverUri;
        this.iEvent = iEvent;

        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
    }

    public boolean isConnectFlag() {
        return connectFlag;
    }

    public void setConnectFlag(boolean connectFlag) {
        this.connectFlag = connectFlag;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.e(TAG, "onOpen");
        connectFlag = true;

        handler.post(new Runnable() {
            @Override
            public void run() {
                iEvent.onConnect();
            }
        });
        //开始心跳
        handler.sendEmptyMessage(HEARTBEAT_MESSAGE_TAG);
    }

    @Override
    public void onMessage(String message) {
        if (message.equals(HEARTBEAT_MESSAGE)) {
            Log.d(TAG, "收到心跳消息");
            return;
        }
        Log.e(TAG, "onMessage: " + message);

        handler.post(new Runnable() {
            @Override
            public void run() {
                iEvent.onMessage(message);
            }
        });
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.e(TAG, "onClose:" + reason + ",remote:" + remote + ", code:" + code);
        if (connectFlag) {
            restartConnect();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    iEvent.reConnect();
                }
            });

        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    iEvent.onDisconnect();
                }
            });

        }
    }

    @Override
    public void onError(Exception ex) {
        Log.e("dds_error", "onError${ex.message}" + ex.getMessage());
    }


    private Handler handler = new Handler(Looper.getMainLooper()) {
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == HEARTBEAT_MESSAGE_TAG) { //心跳
                if (isOpen()) {
                    Log.d(TAG, "发送心跳");
                    reconnectionNum = 0;
                    YMRtmWebSocketClient.this.sendMessage(HEARTBEAT_MESSAGE);
                    sendEmptyMessageDelayed(HEARTBEAT_MESSAGE_TAG, 10000);
                }
            } else if (msg.what == RESTART_CONNECT_TAG) { //重连
                Log.d(TAG, "重新连接:" + reconnectionNum);
                if (reconnectionNum >= 4) {
                    connectFlag = false;
                    return;
                }
                reconnectionNum++;
                reconnect();
            }
        }
    };

    /**
     * 发送消息
     *
     * @param msg
     */
    private void sendMessage(String msg) {
        if (getConnection().isOpen() && !handler.hasMessages(HEARTBEAT_MESSAGE_TAG)) {
            send(msg);
        }
    }

    /**
     * 重新连接
     */
    private void restartConnect() {
        if (!handler.hasMessages(RESTART_CONNECT_TAG)) {
            //两秒后重新链接
            handler.sendEmptyMessageDelayed(RESTART_CONNECT_TAG, 5000);
        }
    }


}
